import React, { useState, useEffect, useRef } from 'react'
import './chatMes.scss'
import { NavBar, Space } from 'antd-mobile'
import { MoreOutline } from 'antd-mobile-icons'
import { useNavigate, useLocation } from 'react-router-dom'
import Info from '../info/Info'
// 获取用户对话信息
import { getMessage, sendeMessasge } from '../../../../utils/request'

import { io } from 'socket.io-client'
import dayjs from 'dayjs'

const right = (
    <div style={{ fontSize: 24 }}>
        <Space style={{ '--gap': '16px' }}>
            <MoreOutline />
        </Space>
    </div>
)

export default function ChatMes() {
    let navigate = useNavigate();
    let location = useLocation();
    //当前的聊天室
    let conv = location.state.obj
    let socket = useRef()
    // 当前登录的用户ID
    let userId = localStorage.getItem('userId')
    // 获取用户的对话信息
    let [messages, setMessage] = useState([])
    //发送的新的信息
    let [newMessage, setNewMessage] = useState('')

    let [arrivalMessage, setArrivalMessage] = useState(null)

    //用于滚动到最后一条信息
    let scrollRef = useRef()

    useEffect(() => {
        socket.current = io('ws://localhost:8900')
        socket.current.on('getMessage', data => {
            setArrivalMessage({
                sender: data.senderId,
                text: data.text,
                createdAt: Date.now()
            })
        })
    }, [])

    //获取用户
    useEffect(() => {
        socket.current.emit('addUser', userId)
        socket.current.on('getUsers', users => {
            console.log(users);
        })
    }, [userId])

    useEffect(() => {
        arrivalMessage && conv?.members.includes(arrivalMessage.sender) &&
            setMessage((prev) => [...prev, arrivalMessage])
    }, [arrivalMessage, conv])

    // 获取用户对话信息
    useEffect(() => {
        getMessage(location.state.convId).then(res => {
            setMessage(res)
        })
    }, [])

    //发送消息
    const handleSubmit = async () => {
        const message = {
            sender: userId,
            text: newMessage,
            conversationId: location.state.convId
        }

        //实时发送消息
        socket.current.emit('sendMessage', {
            senderId: userId,
            receiverId: location.state.user._id,
            text: newMessage,
        })

        sendeMessasge(message).then(res => {
            setMessage([...messages, res])
            setNewMessage('')
        })

    }

    //将页面滚动到最新的消息
    useEffect(() => {
        scrollRef.current?.scrollIntoView({ behavior: "smooth" })
    }, [messages])

    const back = () => {
        navigate(-1)
        // socket.current.emit('disconnect')
    };
    return (
        <div className='chatMes'>
            <div className='chatMes-top'>
                <NavBar right={right} onBack={back}>
                    <span>{location.state.user.userName}</span>
                </NavBar>
            </div>
            <div className='chatMes-center'>
                {
                    messages.map((item, index) => {
                        if (index === 0) {
                            return <div key={item._id} ref={scrollRef}>
                                <p style={{ textAlign: "center" }}>{dayjs(item.createdAt).format('YYYY-MM-DD HH:mm')}</p>
                                <Info message={item} own={item.sender === userId} />
                            </div>
                        } else {
                            const lastTime = new Date(messages[index - 1].createdAt)
                            const newTime = new Date(item.createdAt)
                            const time = (newTime - lastTime) / (1000 * 60)
                            if (time > 5) {
                                return <div key={item._id} ref={scrollRef}>
                                    <p style={{ textAlign: "center" }}>{dayjs(item.createdAt).format('YYYY-MM-DD HH:mm')}</p>
                                    <Info message={item} own={item.sender === userId} />
                                </div>
                            } else {
                                return <div key={item._id} ref={scrollRef}>
                                    <Info message={item} own={item.sender === userId} />
                                </div>
                            }
                        }
                    })
                }
            </div>
            <div className='chatMes-foot'>
                <div className='chatMes-foot-top'>
                    <input type="text"
                        placeholder='请输入内容'
                        value={newMessage}
                        onChange={(e) => { setNewMessage(e.target.value) }}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter') {
                                handleSubmit()
                            }
                        }}
                    />
                    <span>
                        <img src="/纸飞机.png" alt="" onClick={handleSubmit} />
                    </span>
                </div>
            </div>
        </div>
    )
}

